package ch.fhnw.qualiscan.core.libraries;

import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import ch.fhnw.qualiscan.AppObject;
import ch.fhnw.qualiscan.application.pages.PageNotFound;
import ch.fhnw.qualiscan.application.pages.PermissionDenied;
import ch.fhnw.qualiscan.application.pages.Start;
import ch.fhnw.qualiscan.core.Page;
import ch.fhnw.qualiscan.core.helpers.SessionHelper;
import eu.livotov.tpt.TPTApplication;
/**
 * LoaderLib load the pages in to the layout. It also checks if the user has the necessary permissions to load this library.
 * @author Kevin Mettenberger
 *
 */
@SuppressWarnings("serial")
public class LoaderLib implements Serializable {
	
	/**
	 * Object of the current page
	 */
	
	public AppObject dataObject;
	
	
	public LoaderLib()
	{	
		dataObject = (AppObject) TPTApplication.getCurrentApplication().getMainWindow().getData();
	}
    /**
     * This function takes care of authentication and permissions.
     * 
     * @return true if the user has access to the requested page.
     * @param page the requested Page.
     */
    public boolean getAccess(Page page){
    	SessionHelper sessionHelper = new SessionHelper();
    	int counter = 0;
    	if (page.neededPermissions.isEmpty()) {
    		return true;
    	}
   
    	if (page.neededPermissions.contains("loggedIn") && sessionHelper.isUserSessionSet() && page.neededPermissions.size() == 1) {
    		return true;
    	}
    	
    	Method m;
    	Object o;
    	
    	if (sessionHelper.isUserSessionSet()) {
	    	for (int i = 0; i < page.neededPermissions.size(); i++) {
	    		if(page.neededPermissions.get(i) != "loggedIn") {
		    		try {
		    			String method = page.neededPermissions.get(i).toLowerCase();
		    			method = method.substring(0,1).toUpperCase() + method.substring(1);
		    			m = sessionHelper.getUserSession().getRole().getPermissions().getClass().getDeclaredMethod("get"+method);
		    		}
		    		catch(NoSuchMethodException e) {
		    			return false;
		    		}
		    		
		    		try {
		    		 o = m.invoke(sessionHelper.getUserSession().getRole().getPermissions());
		    		}
		    		catch(InvocationTargetException e) {
		    			return false;
		    		}
		    		catch(IllegalAccessException e) {
		    			return false;
		    		}
		    		
		    		if((Integer)o != 1) {
		    			counter = 1;
		    		}
	    		}
	    	}
	    	
	    	if (counter == 0) {
	    		return true;
	    		
	    	}
    	}
    	return false;
    }
    
    /**
     * Loads the requested page.
     * @param page the page to be loaded.
     */
    public void loadPage(Page page) {
    	if (getAccess(page)) {
    		dataObject.getBaseLayout().page.removeAllComponents();
    		dataObject.setCurrentPage(page);

    		dataObject.getBaseLayout().page.addComponent(page);
    		page.init();
    		
    	}
    	else {
    		loadPage(new PermissionDenied());
    	}
    }
    
    /**
     * This function is pivotal for loading new content. As soon as a fragment has changed, this function is called by the HistoryLib.
     * It will load either the demanded controller if it exists in ch.fhnw.qualiscan.controller or it will display 404-page.
     * @param fragment Name of the demanded controller.
     */
    public void loadPage(String fragment) {
    	if(fragment.equals("")) {
    		loadPage(new Start());
    	} else {
	    	try {
	    		Class<?> newPage = null;
	    		
	    		try {
	    			newPage = Class.forName("ch.fhnw.qualiscan.application.pages." + fragment);
	    		} catch(Exception ClassNotFoundException) {
	    			newPage = null;
	    		}
	    		
	            if(newPage != null) {
	            	Object object = newPage.newInstance();
	            	loadPage((Page) object);
	            } else {
	            	loadPage(new PageNotFound());
	            }
	            
	        } catch (Exception ex) {
	        	ex.printStackTrace();
	        }
    	}
    }
    
}


